<template>
    <div class="table-box">
        <!-- 新增统计卡片 -->
        <el-row class="stats-container" gutter="24">
            <el-col :span="12">
                <el-card class="stats-card" shadow="never">
                    <div class="stats-item">
                        <p class="stats-title">总产品数</p>
                        <div class="stats-content">
                            <span class="main-value">{{ product.productNums }}</span>
                            <span class="growth-rate positive"> 本月新增{{ product.thisMonth }}</span>
                        </div>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="12">
                <el-card class="stats-card" shadow="never">
                    <div class="stats-item">
                        <p class="stats-title">在售产品</p>
                        <div class="stats-content">
                            <span class="main-value">{{ product.sellProduct }}</span>
                            <span class="growth-rate positive"> 本月新增在售 {{ product.thisMonthSell }}</span>
                        </div>
                    </div>
                </el-card>
            </el-col>
        </el-row>

        <ProTable ref="proTable" title="用户列表" :columns="columns" :request-api="getTableList" :init-param="initParam"
            :data-callback="dataCallback">
            <!-- 表格 header 按钮 -->
            <template #tableHeader="scope">
                <el-button type="primary" class="standard-btn" :icon="CirclePlus" @click="openDiolg('新增', null)">
                    添加新产品
                </el-button>
                <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
                <el-button type="info" plain icon="PriceTag" @click="openPriceDiolg">
                    批量调价
                </el-button>
                <el-button type="info" plain icon="Setting" @click="openOrdereDiolg">
                    批量设置起订量
                </el-button>
                <el-button type="info" plain icon="PriceTag" @click="handleBatchOperation">
                    批量操作
                </el-button>
            </template>
            <!-- 表格操作 -->
            <template #operation="scope">
                <el-button type="primary" link :icon="View" @click="openDiolg('查看', scope.row)">
                    查看
                </el-button>
                <el-button type="primary" link :icon="EditPen" @click="openDiolg('编辑', scope.row)">
                    编辑
                </el-button>
                <el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">
                    删除
                </el-button>
            </template>
        </ProTable>
        <ExcelUpload ref="ExcelRef" title="导入demo" type="1" :templateParams="templateParams">
        </ExcelUpload>

        <el-dialog title="批量操作" v-model="batchDialogVisible" width="500px" :close-on-click-modal="false" append-to-body>
            <el-radio-group v-model="batchOperationType" class="batch-operation-group">
                <el-radio :label="1" size="large">
                    <span class="operation-label batch-up">批量上架</span>
                </el-radio>
                <el-radio :label="2" size="large">
                    <span class="operation-label batch-down">批量下架</span>
                </el-radio>
                <el-radio :label="3" size="large">
                    <span class="operation-label batch-delete">批量删除</span>
                </el-radio>
            </el-radio-group>

            <template #footer>
                <el-button @click="batchDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmBatchOperation">确定</el-button>
            </template>
        </el-dialog>
    </div>

    <priceForm ref="priceDialogRef"></priceForm>
    <orderForm ref="orderDialogRef"></orderForm>
</template>



<script setup lang="tsx" name="useProTable">
import { ref, reactive, getCurrentInstance, toRefs, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox, tabBarProps } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import {
    ColumnProps,
} from "@/components/ProTable/interface";
import {
    CirclePlus,
    Delete,
    EditPen,
    Download,
    Upload,
    View,
    Refresh,
} from "@element-plus/icons-vue";
import {
    deviceNumList,
    devTypeList,
    devOnlineStatusList,
    devUseStatusList,
    findLabel,
} from "@/utils/stata";
import {
    listProduct,
    getProduct,
    delProduct,
    addProduct,
    updateProduct,
    productNum,
    updown,
    getPrice,
    updateProductConfig,
    getMinimimOrder
} from "@/api/zc/productLibrary";
import {
    listWithFather
} from "@/api/zc/classification";
import priceForm from "./priceForm.vue";
import orderForm from "./orderForm.vue"
import { getDicts } from "@/api/system/dict/data";
import { useHandleData } from "@/hooks/useHandleData";
const proxy = getCurrentInstance()?.proxy;
const emit = defineEmits(["changeItem"]);
const { sys_user_sex } = toRefs<any>(proxy?.useDict("sys_user_sex"));
const router = useRouter();
const ExcelRef = ref(null);
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<any>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ type: 1 });

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
    return { list: data.rows, total: data.total };
};

const product = ref({});
// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
    productNum().then(res => {
        console.log(res);
        product.value = res.data;
    })
    return listProduct(params);
};
const templateParams = {
    templateName: "demo模板",
    templateUrl: "system/user/importTemplate",
    templateType: 0,
    templateObj: {}
}

// 表格配置项
const columns = [
    {
        type: "selection",
        fixed: "left",
        width: 80
    },
    { type: "index", label: "序号", width: 80, fixed: "left" },
    {
        prop: 'productCode',
        label: '产品代码',
        search: {
            el: 'input'
        }
    },
    {
        prop: 'productUrl',
        label: '产品图片',
        render: (scope: any) => {
            return (
                <el-image
                    class="table-img"
                    src={scope.row.productUrl}
                    zoom-rate={1.2}
                    max-scale={7}
                    min-scale={0.2}
                    preview-src-list={[scope.row.productUrl]}
                    fit="cover"
                    preview-teleported
                />
            )
        },
    },
    {
        prop: 'productName',
        label: '产品名称',
        search: {
            el: 'input'
        }
    },
        {
        prop: 'price',
        label: '单价',
        render: (scope) => {
            if(scope.row.unitPriceBefore){
                 return scope.row.unitPriceBefore + '-' + scope.row.unitPriceBefore + '元';
            }else{
                return '暂无价格';
            }
         
        },
    },
    {
        prop: 'classifyId',
        label: '系列',
        search: {
            el: 'select'
        },
        fieldNames: {
            label: "childName",
            value: "id",
        },
        enum: async () => {
            let { data } = await listWithFather({ pageNum: 1, pageSize: 9999, fatherName: '产品系列', });
            return { data };
        },
    },
    //     {
    //     prop: 'productSituation',
    //     label: '上下架',
    //     render: (scope) => {
    //         const status = scope.row.productSituation;
    //         const statusInfo = status === 0
    //             ? { text: '上架', type: 'success' }
    //             : { text: '下架', type: 'danger' };

    //         return (
    //             <el-tag type={statusInfo.type} effect="light">
    //                 {statusInfo.text}
    //             </el-tag>
    //         );
    //     },
    //     enum: [
    //         {
    //             label: '上架',
    //             value: 0
    //         },
    //         {
    //             label: '下架',
    //             value: 1
    //         },
    //     ],
    //     search: {
    //         el: 'select'
    //     }
    // },
    {
        prop: 'status',
        label: '状态',
        render: (scope) => {
            if (scope.row.status == 0) {
                return <el-tag type="primary">在售</el-tag>
            } else if (scope.row.status == 1) {
                return <el-tag type="danger">停售</el-tag>
            } else if (scope.row.status == 2) {
                return <el-tag type="primary">新品</el-tag>
            }
        },
        enum: [
            {
                label: '在售',
                value: 0
            },
            {
                label: '停售',
                value: 1
            },
            {
                label: '新品',
                value: 2
            }
        ],
        search: {
            el: 'select'
        }
    },
    {
        prop: 'material',
        label: '材质',
        search: {
            el: 'select'
        },
        fieldNames: {
            label: "childName",
            value: "childName",
        },
        enum: async () => {
            let { data } = await listWithFather({ pageNum: 1, pageSize: 9999, fatherName: '产品材质', });
            return { data };
        },
    },
    {
        prop: 'style',
        label: '风格',
        search: {
            el: 'select'
        },
        fieldNames: {
            label: "childName",
            value: "childName",
        },
        enum: async () => {
            let { data } = await listWithFather({ pageNum: 1, pageSize: 9999, fatherName: '产品风格', });
            return { data };
        },
    },
    // {
    //     prop: 'productDesign',
    //     label: '产品设计图'
    // },
    {
        prop: 'createTime',
        label: '创建时间',
        search: {
            el: 'date-picker',
            span: 1,
            props: {
                type: 'date',
                valueFormat: 'YYYY-MM-DD HH:mm:ss'
            }
        }
    },
    {
        prop: 'operation',
        label: '操作',
        fixed: 'right',
        width: 330
    }
];

const changeStatus = async (row: any, key: string) => {
    // await useHandleData(updateSign, { ...row, key: row[key] == 1 ? 0 : 1 }, `切换状态`);
    await updateProduct({ ...row, key: row[key] == 1 ? 0 : 1 });
    ElMessage.success({ message: `调整合作状态成功！` });
    proTable.value?.getTableList();
};
// 删除用户信息
const deleteAccount = async (params: any) => {
    const ids = params.id
    await useHandleData(delProduct, ids, '是否删除编号为' + ids + '的数据');
    proTable.value.getTableList();
};
//模拟 调用接口
const PromiseDel = () => new Promise((resolve, reject) => resolve(true))

/** 导出按钮操作 */
function handleExport() {
    console.log("导出",proTable.value?.selectedListIds);
    let ids = proTable.value.selectedListIds.join(',')
    proxy.download("product/product/export", {
        ids
    }, `产品_${new Date().getTime()}.xlsx`);
};
// 批量操作弹窗控制
const batchDialogVisible = ref(false);
const batchOperationType = ref<1 | 2 | 3>(1); // 1=上架 2=下架 3=删除
const selectedRows = ref<number[]>([]);

// 批量操作入口函数
const handleBatchOperation = () => {
    console.log("批量操作", proTable.value.selectedListIds);
    selectedRows.value = proTable.value?.selectedListIds || [];

    if (selectedRows.value.length === 0) {
        ElMessage.warning("请先选择需要操作的产品");
        return;
    }

    // 重置操作类型并显示弹窗
    batchOperationType.value = 1;
    batchDialogVisible.value = true;
};

// 确认执行批量操作
const confirmBatchOperation = async () => {
    const operationMap: Record<number, { message: string, title: string, confirmText: string }> = {
        1: {
            message: `确定要将选中的 ${selectedRows.value.length} 个产品上架吗？`,
            title: '批量上架确认',
            confirmText: '上架'
        },
        2: {
            message: `确定要将选中的 ${selectedRows.value.length} 个产品下架吗？`,
            title: '批量下架确认',
            confirmText: '下架'
        },
        3: {
            message: `确定要删除选中的 ${selectedRows.value.length} 个产品吗？此操作不可恢复！`,
            title: '批量删除确认',
            confirmText: '删除'
        }
    };

    const operation = operationMap[batchOperationType.value];

    try {
        await ElMessageBox.confirm(
            operation.message,
            operation.title,
            {
                confirmButtonText: operation.confirmText,
                cancelButtonText: '取消',
                type: batchOperationType.value === 3 ? 'warning' : 'info',
                dangerouslyUseHTMLString: true
            }
        );

        // 执行相应的API请求
        switch (batchOperationType.value) {
            case 1:
                await updown({ productIds: selectedRows.value, productSituation: batchOperationType.value - 1 });
                break;
            case 2:
                await updown({ productIds: selectedRows.value, productSituation: batchOperationType.value - 1 });
                break;
            case 3:
                await delProduct(selectedRows.value.join(','));
                break;
        }

        ElMessage.success(`${operation.confirmText}操作成功！`);
        batchDialogVisible.value = false;

        // 刷新表格数据
        proTable.value.getTableList();
    } catch (e) {
        console.log('用户取消操作');
    }
};

const priceDialogRef = ref(null)
const openPriceDiolg = async (title: string, row: any) => {
    let { data: priceReqList } = await getPrice();
    let { data: minimimOrderReqList } = await getMinimimOrder();
    const params = {
        title: "批量调价",
        isView: "批量调价",
        rowData: {
            priceReqList, minimimOrderReqList
        },
        module: "double",//对应模块
        api: updateProductConfig,
        getTableList: proTable.value?.getTableList,
    };
    priceDialogRef.value?.acceptParams(params);
};
const orderDialogRef = ref(null);
const openOrdereDiolg = async (title: string, row: any) => {
    let { data: priceReqList } = await getPrice();
    let { data: minimimOrderReqList } = await getMinimimOrder();
    const params = {
        title: "批量设置起订量",
        isView: "批量设置起订量",
        rowData: {
            priceReqList, minimimOrderReqList
        },
        module: "double",//对应模块
        api: updateProductConfig,
        getTableList: proTable.value?.getTableList,
    };
    orderDialogRef.value?.acceptParams(params);
};
const openDiolg = async (title: string, rowData: any) => {
    let params: any = {
        title,
        isView: title === "查看",
        rowData: { ...rowData },
        api: title === "新增" ? addProduct : title === "编辑" ? updateProduct : undefined,
        getTableList: proTable.value?.getTableList,
    };
    if (title === "新增") {
        params.rowData.zcSupplierCertList = []
    } else {
        let { data } = await getProduct(rowData.id)
        params.rowData = data;
    }
    emit("changeItem", "1", params, title);
};


onMounted(() => {
    setTimeout(() => {
        const { add, ...query } = router.currentRoute.value.query;
        if (add == 0) {
            openDiolg('新增', null)

            // 成功后移除add参数
            router.replace({ query });
        }
    }, 1000)
})
</script>
<style lang="scss" scoped>
// 新增统计卡片样式
.stats-container {
    margin: 0 24px 24px; // 与表格保持边距一致

    .stats-card {
        height: 100%;
        padding: 20px;
        border-radius: 8px;
        background: #fff;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

        .stats-item {
            .stats-title {
                font-size: 14px;
                color: #606266;
                margin-bottom: 8px;
                font-weight: bold;
            }

            .stats-content {
                display: flex;
                align-items: center;
                gap: 12px;

                .main-value {
                    font-size: 24px;
                    font-weight: 600;
                    color: #303133;
                }

                .growth-rate {
                    font-size: 14px;
                    color: #67c23a; // 绿色表示增长

                    &.negative {
                        color: #f56c6c; // 红色表示下降
                    }
                }
            }
        }
    }
}
</style>